/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.agenda.client.view;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JOptionPane;
import com.agenda.PrincipalCliente;
import com.agenda.client.ClienteServidor;
import com.agenda.client.Recursos;
import com.agenda.client.RequisicaoAoClienteThread;
import com.agenda.client.SalaChatLadoCliente;
import com.agenda.client.listeners.OuvidorStatusListener;
import com.agenda.client.listeners.RecebimentoClienteListener;
import com.agenda.client.listeners.UsuariosSelecionadosListener;
import com.agenda.client.requisicoes.AtualizarStatusCompromissoRequisicao;
import com.agenda.client.requisicoes.SolicitarChatRequisicao;
import com.agenda.model.Compromisso;
import com.agenda.model.Convite;
import com.agenda.model.RespostaRequisicao;
import com.agenda.model.Sala;
import com.agenda.model.Usuario;
import com.agenda.model.UsuarioIP;

/**
 *
 * @author Murilo
 */
public class AgendaView extends javax.swing.JFrame implements OuvidorStatusListener, UsuariosSelecionadosListener, RecebimentoClienteListener {

	/**
	 * Creates new form AgendaView
	 */
	public AgendaView() {
		initComponents();
		configurarComponentes();
	}

	/**
	 * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of
	 * this method is always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jScrollPane1 = new javax.swing.JScrollPane();
		contatosList = new javax.swing.JList();
		jPanel1 = new javax.swing.JPanel();
		adicionarCompromisso = new javax.swing.JButton();
		editarCompromissoButton = new javax.swing.JButton();
		confirmarRecusar = new javax.swing.JButton();
		meusCompromissosButton = new javax.swing.JToggleButton();
		chatButton = new javax.swing.JButton();
		sairButton = new javax.swing.JButton();
		jScrollPane2 = new javax.swing.JScrollPane();
		compromissosList = new javax.swing.JList();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("Agenda");
		setPreferredSize(new java.awt.Dimension(800, 600));
		getContentPane().setLayout(new java.awt.BorderLayout(5, 4));

		jScrollPane1.setPreferredSize(new java.awt.Dimension(230, 130));

		contatosList.setModel(new javax.swing.AbstractListModel() {
			String[] strings = { "Item" };

			public int getSize() {
				return strings.length;
			}

			public Object getElementAt(int i) {
				return strings[i];
			}
		});
		contatosList.setMaximumSize(new java.awt.Dimension(150, 80));
		contatosList.setMinimumSize(new java.awt.Dimension(60, 80));
		contatosList.setPreferredSize(new java.awt.Dimension(100, 80));
		jScrollPane1.setViewportView(contatosList);

		getContentPane().add(jScrollPane1, java.awt.BorderLayout.LINE_END);

		jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
		jPanel1.setFont(new java.awt.Font("Sylfaen", 0, 24)); // NOI18N
		jPanel1.setPreferredSize(new java.awt.Dimension(400, 70));
		java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 15, 15);
		flowLayout1.setAlignOnBaseline(true);
		jPanel1.setLayout(flowLayout1);

		adicionarCompromisso.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/agenda/client/view/imagens/calendar_up.png"))); // NOI18N
		adicionarCompromisso.setText("Novo");
		adicionarCompromisso.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				adicionarCompromissoActionPerformed(evt);
			}
		});
		jPanel1.add(adicionarCompromisso);

		editarCompromissoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/agenda/client/view/imagens/document_edit.png"))); // NOI18N
		editarCompromissoButton.setText("Editar");
		editarCompromissoButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				editarCompromissoButtonActionPerformed(evt);
			}
		});
		jPanel1.add(editarCompromissoButton);

		confirmarRecusar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/agenda/client/view/imagens/preferences.png"))); // NOI18N
		confirmarRecusar.setText("Confirmar/Recusar");
		confirmarRecusar.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				confirmarRecusarActionPerformed(evt);
			}
		});
		jPanel1.add(confirmarRecusar);

		meusCompromissosButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/agenda/client/view/imagens/calendar_preferences.png"))); // NOI18N
		meusCompromissosButton.setText("Os Meus");
		jPanel1.add(meusCompromissosButton);

		chatButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/agenda/client/view/imagens/client_network.png"))); // NOI18N
		chatButton.setText("Chat");
		chatButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				chatButtonActionPerformed(evt);
			}
		});
		jPanel1.add(chatButton);

		sairButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/agenda/client/view/imagens/selection_delete.png"))); // NOI18N
		sairButton.setText("Sair");
		sairButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				sairButtonActionPerformed(evt);
			}
		});
		jPanel1.add(sairButton);

		getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

		compromissosList.setModel(new javax.swing.AbstractListModel() {
			String[] strings = { "Item 1", " " };

			public int getSize() {
				return strings.length;
			}

			public Object getElementAt(int i) {
				return strings[i];
			}
		});
		compromissosList.setCellRenderer(new CompromissoListCellRenderer());
		jScrollPane2.setViewportView(compromissosList);

		getContentPane().add(jScrollPane2, java.awt.BorderLayout.CENTER);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void adicionarCompromissoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adicionarCompromissoActionPerformed
		adicionarCompromisso();
	}//GEN-LAST:event_adicionarCompromissoActionPerformed

	private void sairButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sairButtonActionPerformed
		sair();
	}//GEN-LAST:event_sairButtonActionPerformed

	private void editarCompromissoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarCompromissoButtonActionPerformed
		editarCompromisso();
	}//GEN-LAST:event_editarCompromissoButtonActionPerformed

	private void confirmarRecusarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarRecusarActionPerformed
		confirmarRecusarCompromisso();
	}//GEN-LAST:event_confirmarRecusarActionPerformed

	private void chatButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chatButtonActionPerformed
		comecarChat();
	}//GEN-LAST:event_chatButtonActionPerformed
		// Variables declaration - do not modify//GEN-BEGIN:variables

	private javax.swing.JButton adicionarCompromisso;
	private javax.swing.JButton chatButton;
	private javax.swing.JList compromissosList;
	private javax.swing.JButton confirmarRecusar;
	private javax.swing.JList contatosList;
	private javax.swing.JButton editarCompromissoButton;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JToggleButton meusCompromissosButton;
	private javax.swing.JButton sairButton;

	// End of variables declaration//GEN-END:variables

	private List<Usuario> usuariosOnline = new ArrayList<Usuario>();

	private void configurarComponentes() {
		compromissosList.setFixedCellHeight(40);
	}

	@Override
	public void listaClienteAtualizada(List<Usuario> usuariosOnline, List<String> status) {
		this.usuariosOnline = usuariosOnline;
		ArrayList<String> usuariosStatus = new ArrayList<String>();
		int index = 0;
		for (Usuario usuario : usuariosOnline) {
			String tmp = usuario.getLoginEmail() + " " + status.get(index);
			usuariosStatus.add(tmp);
			index++;
		}

		contatosList.setListData(usuariosStatus.toArray());
	}

	@Override
	public void listaCompromissos(List<Compromisso> compromissos) {
		//System.out.println("COMPROMISSOS RETORNADOS _______ " + compromissos);
		if (meusCompromissosButton.isSelected()) {
			List<Compromisso> meusCompromissos = new ArrayList<Compromisso>();
			for (Compromisso compromisso : compromissos) {
				if (compromisso.getProprietario().equals(PrincipalCliente.getUsuarioLogado())
					|| compromisso.isUsuarioConvidado(PrincipalCliente.getUsuarioLogado())) {
					meusCompromissos.add(compromisso);
				}
			}

			compromissosList.setListData(meusCompromissos.toArray());
		} else {

			compromissosList.setListData(compromissos.toArray());
		}
	}

	@Override
	public void erroServidor(String erro) {
		// TODO Auto-generated method stub
	}

	private void adicionarCompromisso() {

		try {
			RespostaRequisicao respo = ClienteServidor.getINSTANCIA().enviarInformacao(new AtualizarStatusCompromissoRequisicao("Criando Evento."));
			if (respo.isErro()) {
				showMessage(respo.getMsg());
				return;
			}

			ClienteServidor.getINSTANCIA().liberarComunicacao();

			CompromissoDialogView compromissoDialogView = new CompromissoDialogView(this, true);
			compromissoDialogView.setCompromisso(new Compromisso());
			compromissoDialogView.setVisible(true);

		} catch (Exception e) {
			ClienteServidor.getINSTANCIA().liberarComunicacao();
			e.printStackTrace();
			showMessage(e.getMessage());
		}
	}

	private void showMessage(String message) {
		JOptionPane.showMessageDialog(this, message);
	}

	private void sair() {
		//PrincipalCliente.sair()
	}

	private void editarCompromisso() {

		try {
			RespostaRequisicao respo = ClienteServidor.getINSTANCIA().enviarInformacao(new AtualizarStatusCompromissoRequisicao("Editando Evento."));

			ClienteServidor.getINSTANCIA().liberarComunicacao();

			if (respo.isErro()) {
				showMessage(respo.getMsg());
				return;
			}

			Compromisso compromisso = (Compromisso) compromissosList.getSelectedValue();

			if (compromisso != null) {
				CompromissoDialogView compromissoDialogView = new CompromissoDialogView(this, true);
				compromissoDialogView.setCompromisso(compromisso);
				compromissoDialogView.setDisableForm(!compromisso.getProprietario().equals(PrincipalCliente.getUsuarioLogado()));

				compromissoDialogView.setVisible(true);
			}
		} catch (Exception e) {
			ClienteServidor.getINSTANCIA().liberarComunicacao();
			e.printStackTrace();
			showMessage(e.getMessage());
		}

	}

	private void confirmarRecusarCompromisso() {
		Compromisso compromisso = (Compromisso) compromissosList.getSelectedValue();
		if (compromisso != null) {
			Convite convite = compromisso.getConvite(PrincipalCliente.getUsuarioLogado());
			if (convite != null) {
				ConfirmarRecusarDialogView confirmarRecusarDialog = new ConfirmarRecusarDialogView(this, true);
				confirmarRecusarDialog.setCompromisso(compromisso);
				confirmarRecusarDialog.setConvite(convite);
				confirmarRecusarDialog.setVisible(true);
			} else {
				showMessage("Você não faz parte desse compromisso.");
			}
		}
	}

	private void comecarChat() {
		List<Usuario> usuarios = new ArrayList<Usuario>(this.usuariosOnline);

		UsuariosListDialogView usuariosDialog = new UsuariosListDialogView(this, true);
		usuariosDialog.setLocationRelativeTo(this);
		usuariosDialog.setUsuarios(usuarios);
		usuariosDialog.setUsuariosListener(this);
		usuariosDialog.setVisible(true);
	}

	@Override
	public void selecionou(List<Usuario> usuarios) {

		ClienteServidor clienteServidor = ClienteServidor.getINSTANCIA();

		try {

			Sala sala = new Sala();

			sala.setProprietario(PrincipalCliente.getUsuarioLogado());
			ArrayList<Usuario> usuariosOnLineSemOCorrente = new ArrayList<Usuario>(usuarios);
			usuariosOnLineSemOCorrente.remove(PrincipalCliente.getUsuarioLogado());
			sala.setConvidados(usuariosOnLineSemOCorrente);

			RespostaRequisicao resposta = clienteServidor.enviarInformacao(new SolicitarChatRequisicao(sala));

			if (resposta.isErro()) {
				showMessage("Erro:" + resposta.getMsg());
				return;
			}

			ArrayList<UsuarioIP> usuariosIP = (ArrayList<UsuarioIP>) ClienteServidor.getINSTANCIA().lerObjeto();
			SalaChatLadoCliente salaChat = new SalaChatLadoCliente();
			salaChat.setUsuariosIP(usuariosIP);

			ClienteServidor.getINSTANCIA().addRecebimentoListener(salaChat);

			salaChat.enviarRequisicoes();

		} catch (Exception e) {
			showMessage("Erro:" + e.getMessage());
		} finally {
			ClienteServidor.getINSTANCIA().liberarComunicacao();
		}
		//Criar canal de recebimento do servidor, independente do canal principal...
		//Barril....

	}

	@Override
	public void receber(int requisiciao, ConcurrentHashMap<String, Object> valores) {

		System.out.println(" ----- RECEBEU SOLICITACAO DE CHAT..." + valores);
		if (requisiciao == RequisicaoAoClienteThread.SOLICITACAO_CHAT) {

			UsuarioIP userIp = (UsuarioIP) valores.get("usuario");

			boolean liberou = Recursos.getINSTANCE().registrarAtividade();

			boolean confirmou = false;

			if (liberou) {
				int opcao = JOptionPane.showConfirmDialog(this, "O usuário '" + valores.get("usuario")
					+ "' lhe convidou para bater papo. Deseja aceitar?", "Pergunta.", JOptionPane.YES_NO_OPTION);

				confirmou = (opcao == JOptionPane.YES_OPTION);
			}

			SalaChatLadoCliente salaLadoCliente = new SalaChatLadoCliente();
			salaLadoCliente.setRoot(userIp);
			salaLadoCliente.setSala((Sala) valores.get("sala"));

			if (confirmou)
				ClienteServidor.getINSTANCIA().addRecebimentoListener(salaLadoCliente);

			salaLadoCliente.confirmarRecusarSolicitacao(confirmou);

		}

	}
}
